package com.ithl.educenter.controller;

import com.google.gson.Gson;
import com.ithl.commonutils.utils.JwtUtils;
import com.ithl.educenter.entity.UcenterMember;
import com.ithl.educenter.service.UcenterMemberService;
import com.ithl.educenter.utils.ConstantVxUtils;
import com.ithl.educenter.utils.HttpClientUtils;
import com.ithl.serviceutils.exchandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author hl
 * @Data 2020/4/24
 */
@Controller
//@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Autowired
    private UcenterMemberService memberService;

    /**
     * 微信扫码登陆 根据 code 取得 accessToken openid 然后用openid 获取用户信息 和 拿取数据存入数据
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        try {
            //1 向认证服务器发送请求换取access_token openId
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantVxUtils.WX_OPEN_APP_ID,
                    ConstantVxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            // 2 请求这个地址的到access_token 和 openid 请求这个地址的到access_token 和 openid
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
/*          "access_token":"32_KN-mIqjHC3zAuU8Xd3UB7YwLIlO1vCWo16xYgvom7H0jmM-hG0_DYy59cwNH24UxZXRFneE9XdF33GK9LNLnalIEI_rnuW435xcY00xDbeo",
            "expires_in":7200,
            "refresh_token":"32_O--Q8crew5bYpYU35qKbgl-A0BVleMLfwLe569c_dC4e1miZmIEj_pOt8bVbTInxKTPptki7rETfYZchwhiCEwhs7JcLiD5X92O9lrVIjDA",
            "openid":"o3_SC5_ZXjNhuEx6syqb_lVasXms",
            "scope":"snsapi_login",
            "unionid":"oWgGz1GwK_tcs52fRi6fMZn_0iiQ"}*/
//          转换为json
            Gson gson = new Gson();
            HashMap accessTokenInfoMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) accessTokenInfoMap.get("access_token");
            String openid = (String) accessTokenInfoMap.get("openid");
            // 把用户信息放入数据库
            UcenterMember member = memberService.getByOpenId(openid);
            // 没有相同的就添加  if有就直接跳转
            String jwtToken = "";
            if (member == null) {
                //  3 请求地址 去求扫描人的信息 然后放入数据库
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
            /*
            {"openid":"o3_SC5_ZXjNhuEx6syqb_lVasXms","nickname":"kilig","sex":1,"language":"zh_CN","city":"Chengdu","province":"Sichuan","country":"CN","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/DYAIOgq83erqPQcbrNpo7S9sI08opAOT3FACha1fANjPicLMOUmSEgD5v4OpiaiaX7zjotbGLn2D0hGevfnRMYiabw\/132","privilege":[],"unionid":"oWgGz1GwK_tcs52fRi6fMZn_0iiQ"}
             */
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname"); // 昵称
                String headimgurl = (String) userInfoMap.get("headimgurl"); // 头像
                UcenterMember ucenterMember = new UcenterMember();
                ucenterMember.setOpenid(openid);
                ucenterMember.setNickname(nickname);
                ucenterMember.setAvatar(headimgurl);
                memberService.save(ucenterMember);
                jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
            } else {
                jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            }
//            使用token解决跨域
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new MyException(1, "扫描失败");
        }
    }

    // 1。请求一个地址 生成微信二维码
    @GetMapping("/loginByWx")
    public String loginByWx() {
        // 固定地址 1, 拼接  ?appid=dhadh&dada=ad 2、使用 %s 占位 然后使用String的format(推荐)
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 对redirect_url进行编码
        String redirectUrl = ConstantVxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException("转码出现错误");
        }
        String url = String.format(
                baseUrl,
                ConstantVxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "ithl"
        );
        // 请求微信地址
        return "redirect:" + url;
    }
}
